package democache;

import democache.computer.Computable;
import democache.computer.MayFail;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Brook
 * 缓存污染和发生错误的问题演示
 */
public class DemoCache9<A, V> implements Computable<A, V> {

    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public DemoCache9(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException {

        while (true) {
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> callable = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<>(callable);

                f =cache.putIfAbsent(arg,ft);
                if(f == null){
                    f = ft;
                    System.out.println("从FutrureTasl调用了计算函数");
                    ft.run();
                }
            }
            try {
                return f.get();
            } catch(CancellationException e) {
                System.out.println("被取消了");
                cache.remove(arg);
                throw e;
            }catch (InterruptedException e) {
                cache.remove(arg);
                throw e;
            } catch (ExecutionException e) {
                System.out.println("计算错误，需要重试");
                cache.remove(arg);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        DemoCache9<String, Integer> demoCache2 = new DemoCache9(new MayFail());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第一次计算结果："+result);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Integer result = null;
                try {
                    result = demoCache2.compute("666");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("第三次计算结果："+result);
            }
        }).start();
    }
}
